package com.simon.app.october.common.aspect;

import com.google.gson.Gson;
import com.simon.app.october.common.annotation.SysLog;
import com.simon.app.october.common.utils.HttpContextUtils;
import com.simon.app.october.common.utils.IPUtils;
import com.simon.app.october.modules.sys.dao.SysLogDao;
import com.simon.app.october.modules.sys.entity.SysLogEntity;
import com.simon.app.october.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogDao sysLogDao;

    /**
     * 定义一个切点
     * */
    @Pointcut("@annotation(com.simon.app.october.common.annotation.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method          method    = signature.getMethod();
        long            startTime = System.currentTimeMillis();
        SysLogEntity    entity    = new SysLogEntity();
        SysLog          sysLog    = method.getAnnotation(SysLog.class);
        if (sysLog != null) {
            entity.setOperation(sysLog.value());
        }
        entity.setMethod(signature.getDeclaringTypeName()+"."+method.getName());
        entity.setParams(new Gson().toJson(point.getArgs()));
        Object result = point.proceed();

        // 获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        // 获取IP
        entity.setIp(IPUtils.getIpAddr(request));

        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        entity.setUsername(user.getUsername());

        entity.setCreateDate(new Date());

        // 设置执行时间
        entity.setTime(System.currentTimeMillis() - startTime);

        sysLogDao.insert(entity);
        return result;
    }
}
